package com.lcf.system.manager;

import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.lcf.framework.exception.SysException;
import com.lcf.framework.model.BaseModel;
import com.lcf.framework.vo.BaseVO;
import com.lcf.framework.vo.PageVO;
import com.lcf.system.entity.SysUser;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 用户
 * @author lcf
 */
@Component
public class SysUserManager {
    /**
     * 检查用户是否存在
     */
    public void checkExist(Long id, SysUser dto) {
        SysUser sysUser = Db.lambdaQuery(SysUser.class)
                .eq(SysUser::getUsername, dto.getUsername())
                .ne(id != null, SysUser::getId, id)
                .one();

        if (sysUser != null) {
            if (Objects.equals(sysUser.getUsername(), dto.getUsername())) {
                throw new SysException("用户名已存在!");
            }
        }
    }

    /**
     * 检查id
     */
    public void checkId(long id) {
        SysUser sysUser = Db.lambdaQuery(SysUser.class).eq(SysUser::getId, id).one();
        if (sysUser == null) {
            throw new SysException("用户不存在");
        }
    }

    /**
     * 填充列表创建人姓名和更新人姓名
     */
    public <T extends BaseVO> List<T> setUserName(List<T> list) {
        if (CollectionUtils.isEmpty(list)) {
            return list;
        }

        List<Long> userIdList = list.stream()
                .flatMap(x -> Stream.of(x.getCreateBy(), x.getUpdateBy()))
                .filter(Objects::nonNull)
                .distinct().toList();

        Map<Long, String> userMap = Db.lambdaQuery(SysUser.class)
                .in(SysUser::getId, userIdList)
                .list().stream()
                .collect(Collectors.toMap(BaseModel::getId, SysUser::getName));

        list.forEach(x -> {
            x.setCreateUser(userMap.get(x.getCreateBy()));
            if (x.getUpdateBy() != null) {
                x.setUpdateUser(userMap.get(x.getUpdateBy()));
            }
        });
        return list;
    }

    /**
     * 填充列表创建人姓名和更新人姓名
     */
    public <T extends BaseVO> PageVO<T> setPageUserName(PageVO<T> page) {
        this.setUserName(page.getList());
        return page;
    }
}
